package com.example.demo.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

/**
 * Copyright (C), 2015-2020
 * FileName: CustomFilter
 * Author:   MRC
 * Date:     2020/1/1 10:52
 * Description: 默认过滤器
 * History:
 */
public class CustomFilter extends ZuulFilter {

    private Logger logger = LoggerFactory.getLogger(CustomFilter.class);


    /**
     * @Author MRC
     * @Description 指定路由类型
     * pre：可以在请求被路由之前调用
     * routing：在路由请求时候被调用
     * post：在routing和error过滤器之后被调用
     * error：处理请求时发生错误时被调用
     * @Date 11:01 2020/1/1
     * @Param []
     * @return java.lang.String
     **/
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * @Author MRC
     * @Description 路由开关。
     * @Date 11:01 2020/1/1
     * @Param []
     * @return boolean
     **/
    @Override
    public boolean shouldFilter() {
        return true;
    }
    
    /***
     * @Author MRC
     * @Description //TODO 过滤器实现逻辑
     * @Date 10:53 2020/1/1
     * @Param []
     * @return java.lang.Object
     **/
    @Override
    public Object run() throws ZuulException {

        logger.info("start to filter");

        RequestContext requestContext = RequestContext.getCurrentContext();

        HttpServletRequest request = requestContext.getRequest();

        //从头部取出token
        String token = request.getHeader("token");


        if (null == token) {
            logger.warn("非法请求");

            //进行拦截
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(401);
            return null;
        }
        logger.info("request success");

        return null;
    }
}